﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;

using System.Threading;
using System.Diagnostics;
using EITSurferInfinityLib.DataProcessing;


namespace EITSurferInfinityLib
{
    public class VirtualDevice
    {
        public PhysicalUnitParameter ToVoltParameter;

        IDriver Device;
        FilePlayer fp;
        List<SimpleData> sd;
        oeit oeitfile;
        IDataInterpreter di;

        public delegate void OnMessageHandler(object sender, EventArgsMsg e);
        public event OnMessageHandler OnMessage;

        public delegate void OnSimpleDataHandler(object sender, EventArgsSimpleData e);
        public event OnSimpleDataHandler OnSimpleData;

        public delegate void OnReconstructedImageHandler(object sender, EventArgs e);
        public event OnReconstructedImageHandler OnReconstructedImage;

        public delegate void OnRawDataHandler(object sender, EventArgsRawData e);
        public event OnRawDataHandler OnRawData;

        public delegate void OnConnectedHandler(object sender, EventArgs e);
        public event OnConnectedHandler OnConnected;

        System.Timers.Timer timer1;
        System.Timers.Timer timerWaitToStop;
        System.Timers.Timer ReplayTimer;
        int ReplayTimerCounter;
        int timerWaitToStop_counter;
        string timerWaitToStop_dirname;
        public bool Saving;
        int timer1Counter;
        int timer1Max;
        bool StartTrigger;
        // bool EnableReconstruction;

        public int FrameCounter;

        public double Frequency;
        public double SettlingTime;
        public double MeasurementTime; //demodulation time = MeasurementTime-SettlingTime
        public int Offset;
        public bool RotateMeasurement;
        public int NumberElectrode;
        public int ImageRate;
        public double ADCSamplingPeriod;
        public double ADCSamplingPeriodMin;

        public string ActiveDirectoryPath;
        public bool Busy;
        public bool BusyRaw;
        public bool BusyFrame;
        public bool IsStopped;
        public bool BusySerial;

        public bool EnableRecordFrames;
        public bool EnableRecordRaw;
        public int EnableReconstruction;

        public double VRefDac { set; get; }
        public double CurrentSourceSettings { set; get; }

        ImageReconstruction IRecontruction;
        public float[] LastData;
        public float[] LastImage;
        public List<double> HistoryMean;

        public string ReplayMode;
        public int ReplayFrame;

        public string DeviceName;

        public int counter_debug;

        public SerialDevice ContactZModule;
        public SerialDevice CurrentSourceTester;
        public SerialDevice Robot;

        string robot_buffer = "";
        string zmodule_buffer = "";
        string currentsourcetester_buffer = "";

        public VirtualDevice(string deviceName)
        {
            DeviceName = deviceName;
            sd = new List<SimpleData>();
            fp = new FilePlayer();
            CreateDevice(DeviceName);
            ToVoltParameter = new PhysicalUnitParameter(0, 0, 0, 0, 0);
            timer1 = new System.Timers.Timer();
            timer1Counter = 0;
            StartTrigger = false;
            Busy = false;
            BusyRaw = false;
            BusyFrame = false;
            IsStopped = true;
            EnableRecordFrames = false;
            EnableRecordRaw = false;
            FrameCounter = 0;
            EnableReconstruction = 0;
            HistoryMean = new List<double>();
            ReplayMode = "none";
            ReplayFrame = 0;
            counter_debug = 0;
            timerWaitToStop = new System.Timers.Timer();
            timerWaitToStop_counter = 0;
            timerWaitToStop.Elapsed += new ElapsedEventHandler(timerWaitToStop_tick);
            Saving = false;
            Offset = 4;
            //fp.OnNewDataAvailable += new FilePlayer.NewDataAvailableEventHandler(fp_OnNewDataAvailable);
        }

        /// <summary>
        /// Creates a specific virtual device using the device name parameter.
        /// </summary>
        /// <param name="deviceName"> 
        /// The device name as the form: xx_y_z.zz_t.t_w
        /// for example: st_1_0.12_3.0_A,
        /// x:manufacturer
        /// y:system code
        /// z:firmware version
        /// t:hardware version
        /// w:hardware subversion
        /// </param>
        public void CreateDevice(string deviceName)
        {
            //loads device specific classes and parameters
            switch (deviceName)
            {
                case "st_1_0.12_3.0_A":
                    Device = new Swisstom0();
                    CurrentSourceSettings = LoadHwP_st_1_xpxx_3p0.GetVtoILinearValue("A");
                    VRefDac = LoadHwP_st_1_xpxx_3p0.GetVRefDac("A");
                    ADCSamplingPeriodMin = LoadHwP_st_1_xpxx_3p0.GetADCSamplingPeriodMin("A");
                    di = new st_datainterpreter_1();
                    RotateMeasurement = false;
                    break;
                case "st_1_0.12_3.0_B":
                    Device = new Swisstom0();
                    CurrentSourceSettings = LoadHwP_st_1_xpxx_3p0.GetVtoILinearValue("B");
                    VRefDac = LoadHwP_st_1_xpxx_3p0.GetVRefDac("B");
                    ADCSamplingPeriodMin = LoadHwP_st_1_xpxx_3p0.GetADCSamplingPeriodMin("B");
                    di = new st_datainterpreter_1();
                    RotateMeasurement = false;
                    break;
                case "st_1_0.111_2.42_B":
                    Device = new Swisstom0();
                    CurrentSourceSettings = LoadHwP_st_1_xpxx_3p0.GetVtoILinearValue("B");
                    VRefDac = LoadHwP_st_1_xpxx_3p0.GetVRefDac("B");
                    ADCSamplingPeriodMin = LoadHwP_st_1_xpxx_3p0.GetADCSamplingPeriodMin("B");
                    di = new st_datainterpreter_1();
                    RotateMeasurement = false;
                    break;
            }

            // connects IDriver specific event
            //Device.OnSimpleData += new SimpleDataEvent(Device_OnSimpleData);
            Device.OnMessage += new MessageEvent(Device_OnMessage);
            //Device.OnRawData += new RawDataEvent(Device_OnRawData);
            Device.OnConnected += new ConnectedEvent(Device_OnConnected);
            Device.OnRawDataFrames += new RawDataFramesEvent(Device_OnRawDataFrames);

            //todo: replay system refactoring
            ReplayTimer = new System.Timers.Timer();
        }

        #region Hardware Event Handling
        private void Device_OnRawDataFrames(object sender, EventArgsRawDataFrames e)
        {
            // store each incomming frame into the oeit data structure
            // if EnableRecordFrames is true
            //counter_debug += e.data.data.Count;
            if (EnableRecordFrames)
            {
                FrameCounter++;
                if (oeitfile == null)
                {
                    //creates a new oeit structure if oeit equal null
                    oeitfile = new oeit();
                }
                for (int i = 0; i < e.data.data.Count; i++)
                {
                    //itterate on the number of frame stored into the list e.data.data
                    oeitfile.AddFrame(e.data.data[i], DateTime.Now.ToBinary()); //to-do config pointer
                    counter_debug++; //to-do remove
                }
            }
            for (int i = 0; i < e.data.data.Count; i++)
            {
                EvaluationInfo eval = di.Evalute(e.data.data[i]);
                switch (eval)
                {
                    case EvaluationInfo.IQA_IQB:
                        ProcessIncommingData(di.GetIQA());
                        break;
                    case EvaluationInfo.Raw:
                        ProcessIncommingADCRaw(di.GetRawData());
                        break;

                }
            }
        }
        private void Device_OnMessage(Object sender, EventArgsMsg e)
        {
            //sends message to the debug output window 
            Debug.WriteLine(e.Sender + " -> " + e.Message);

            //writes logs into the oeit raw log file
            if (oeitfile == null)
            {
                //creates a new oeit structure if oeit equal null
                oeitfile = new oeit();
            }
            oeitfile.AddLogEntry(e.Sender + "\t @ \t" + e.TimeStamp.ToString() + "\t -> \t" + e.Message);

            //reads some status from the system message
            if (e.Message.Contains("Ended Acquisition Data"))
            {
                //if (BusyFrame == true)
                //{
                //    EnableRecordFrames = false;
                //}
                BusyFrame = false;
                IsStopped = true;
            }

            if (e.Message.Contains("Stopped"))
            {
                IsStopped = true;
                if (StartTrigger)
                {
                    StartTrigger = false;
                    Start();
                }
            }

            if (e.Message.Contains("Starting Acquisition Data"))
            {
                IsStopped = false;
                Busy = false;
                FrameCounter = 0;
            }

            //triggers the message function of the GUI or other
            if (OnMessage != null)
                OnMessage(null, e);
        }
        private void Device_OnConnected(object sender, EventArgs e)
        {
            if (OnConnected != null)
                OnConnected(null, null);
        }
        #endregion

        #region hardware
        public void ConnectP2P()
        {
            Device.ConnectP2P();
        }
        public void Connect()
        {
            if (!Device.IsConnected())
            {
                Device.Connect();
            }
            else
            {
                //reconnect
                Disconnect();
                Thread.Sleep(100);
                Device.Connect();
            }
        }
        public void Disconnect()
        {
            if (Device.IsConnected())
            {
                Device.Disconnect();
            }
        }
        public void StopAndStart()
        {
            Busy = true;
            if (IsStopped == false)
            {
                Stop();
                StartTrigger = true;
            }
            else
            {
                Start();
            }
        }
        public bool IsConnected()
        {
            return Device.IsConnected();
        }
        public void Start()
        {
            if (!IsConnected())
            {
                Connect();
            }
            else
            {
                Device.Reset();
                Thread.Sleep(100);
                CheckIfConfigurationChanged();
                Device.Start();
            }
        }
        public void Stop()
        {
            if (IsConnected())
            {
                Device.Stop();
            }
        }
        public void Send(string s)
        {
            Device.Send(s);
        }
        public DeviceInfo GetInfo()
        {
            DeviceInfo di = null;
            if (Device != null)
            {
                di = Device.GetDeviceInfo();
            }
            return di;
        }
        public void SerialRaw(int NumberMeasurement)
        {
            timer1.Elapsed += new ElapsedEventHandler(timer1_tick);
            timer1.Interval = 200;
            timer1Counter = 0;
            timer1Max = NumberMeasurement;
            Busy = true;
            timer1.Start();
        }
        public void SerialFrame(int NumberMeasurement)
        {
            Device.Reset();
            Thread.Sleep(200);
            CheckIfConfigurationChanged();
            BusyFrame = true;
            Device.Send("start " + NumberMeasurement.ToString());
        }
        public void ChangeParameter()
        {

        }
        #endregion

        #region replay
        public void SaveDataToFile()
        {
            Device.Stop();
            oeitfile.Save();
        }
        public void StartReplay()
        {
            ToVoltParameter.AnalogGain = 1;
            ToVoltParameter.CurrentA = 1;
            ToVoltParameter.FloatBits = 24;
            ToVoltParameter.NSample = 300;
            ToVoltParameter.VRef = 2.048;

            fp.Start(fp.GetCurrentFrame());
        }
        public void StopReplay()
        {
            fp.Stop();
        }
        public void ResetReplay()
        {
            StopReplay();
            fp.Reset();
        }
        public void ResumeReplay()
        {
            if ((fp.State == PlayerStates.LiveStopped) || (fp.State == PlayerStates.StaticStopped))
            {
                fp.Start();
            }
            else if ((fp.State == PlayerStates.LiveStreaming) || (fp.State == PlayerStates.StaticStreaming))
            {
                StopReplay();
            }
        }
        public void LoadFile()
        {
            //TODO: get parameter from file

            ToVoltParameter.AnalogGain = 1;
            ToVoltParameter.CurrentA = 1;
            ToVoltParameter.FloatBits = 24;
            ToVoltParameter.NSample = 300;
            ToVoltParameter.VRef = 2.048;

            double[] d = fp.GetAmplitudeMeanHistory(ToVoltParameter);
            HistoryMean.Clear();
            for (int i = 0; i < d.Length; i++)
            {
                HistoryMean.Add(d[i]);
            }
            fp.State = PlayerStates.StaticStopped;
        }
        public int GetCurrentFrame()
        {
            return fp.GetCurrentFrame();
        }
        public void SetCurrentFrame(int index)
        {
            fp.SetCurrentFrame(index);
        }
        public void GetSimpleDataCurrent()
        {

            EventArgsSimpleData eventSimple = new EventArgsSimpleData(fp.GetSimpleData(ReplayTimerCounter));
            //ProcessIncommingData(eventSimple);
        }
        public void GetSimpleDataIndex(int index)
        {

            EventArgsSimpleData eventSimple = new EventArgsSimpleData(fp.GetSimpleData(index));
            ReplayFrame = index;
            //ProcessIncommingData(eventSimple);
        }
        public void GetSimpleAndSetRef(int index)
        {
            //StopReplay();
            SimpleData sd = fp.GetSimpleData(index);
            double[] d = IQDataProcessor.GetAmplitude(sd.I, sd.Q, ToVoltParameter);
            d = IQDataProcessor.RemoveInjectionElectrode(d, Offset, 32);
            float[] temp2 = new float[d.Length];
            for (int i = 0; i < temp2.Length; i++)
            {
                temp2[i] = (float)d[i];
            }
            if (IRecontruction != null)
            {
                IRecontruction.SetRef(temp2);
            }
            DoReconstruction(LastData);
            //ResumeReplay();
        }
        void timer1_tick(object sender, ElapsedEventArgs e)
        {
            if (BusyRaw == false)
            {
                if (timer1Max > timer1Counter)
                {
                    timer1Counter++;
                    BusyRaw = true;
                    Send("raw");
                }
                else
                {
                    timer1.Stop();
                    Busy = false;
                }
            }
        }
        public PlayerStates GetReplayMode()
        {
            return fp.State;
        }
        public int GetFilePlayerCounter()
        {
            return fp.GetCounter();
        }
        #endregion


        public void NewOeitFile(string filename)
        {
            Busy = true;
            oeitfile = new oeit(filename);
            Busy = false;
        }
        public void SaveAsych(string dirname)
        {
            Saving = true;
            timerWaitToStop_dirname = dirname;

            timerWaitToStop.Interval = 200;
            timerWaitToStop_counter = 0;
            timerWaitToStop.Start();
        }
        public void Save(string dirname)
        {
            oeitfile.Save(dirname);
            Debug.WriteLine(">>>>>>>>>>" + counter_debug.ToString());
        }
        void timerWaitToStop_tick(object sender, ElapsedEventArgs e)
        {
            if (Device.IsConnected())
            {
                if (IsStopped == true)
                {
                    //Thread.Sleep(200);
                    timerWaitToStop.Stop();
                    Save(timerWaitToStop_dirname);
                    if (System.IO.File.Exists(oeitfile.GetFileName()))
                    {
                        Saving = false;
                    }
                    else
                    {
                        timerWaitToStop.Start();
                    }
                }
            }
            timerWaitToStop_counter++;
        }
        public string Test()  //todo: change name
        {
            //string s = "";
            //s = Device.GetDataHeader() ;
            //return s;
            Device.Send("get all");
            return "test pressed";
        }

        public void Clear()
        {
            bool restart = false;
            if (IsStopped == false)
            {
                Stop();
                restart = true;
            }
            FrameCounter = 0;
            Device.Reset();
            try
            {
                string TempDir = "temp";
                string[] TempSubDir = System.IO.Directory.GetDirectories(TempDir);
                for (int i = 0; i < TempSubDir.Length; i++)
                {
                    System.IO.Directory.Delete(TempSubDir[i], true);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
            oeitfile = new oeit();
            if (restart == true)
            {
                Start();
            }
        }

        #region Data and image processing
        private void ProcessIncommingData(int[,] data)
        {
            if (data != null)
            {
                double[] d = IQDataProcessor.GetAmplitude(data, ToVoltParameter);
                d = IQDataProcessor.RemoveInjectionElectrode(d, Offset, 32); //todo offset + nel as parameter
                if (LastData == null)
                {
                    LastData = new float[d.Length];
                }
                double tempmean = 0;
                if (d.Length == LastData.Length)
                {
                    for (int i = 0; i < d.Length; i++)
                    {
                        LastData[i] = (float)d[i];
                        tempmean += d[i];
                    }
                    if (fp.State == PlayerStates.LiveStreaming)
                    {
                        HistoryMean.Add(tempmean / d.Length);
                    }

                    EventArgsSimpleData e = new EventArgsSimpleData(di.GetIQA(), di.GetIQB());
                    DoReconstruction(LastData);
                    if (OnSimpleData != null)
                        OnSimpleData(null, e);
                }
            }
        }
        private void ProcessIncommingADCRaw(short[,] data)
        {
            int length = data.GetLength(1);
            RawData rd = new RawData(length);
            for (int i = 0; i < length; i++)
            {
                rd.Signal1[i] = data[0, i];
                rd.Signal2[i] = data[1, i];
            }
            EventArgsRawData e = new EventArgsRawData(rd);
            EnableRecordRaw = true;
            if (EnableRecordRaw)
            {
                string dir = ActiveDirectoryPath;
                if (ActiveDirectoryPath == null)
                {
                    dir = "raw";
                }
                string path = dir + "\\" + Vector2BinFile.GetIncrementalName(dir, "raw");
                Vector2BinFile.Save(path, e.data.Signal1, e.data.Signal2);
            }
            BusyRaw = false;
            if (OnRawData != null)
                OnRawData(null, e);
        }
        public void DoReconstruction(float[] dataIn)
        {
            if (EnableReconstruction > 0)
            {
                if (IRecontruction != null)
                {
                    if (IRecontruction.IsReady(ref dataIn, "InverseLibraries\\Default"))
                    {
                        IRecontruction.Calculate(dataIn);
                        LastImage = IRecontruction.LastReconstructedImage;
                        if (LastImage != null)
                        {
                            if (OnReconstructedImage != null)
                                OnReconstructedImage(null, null);
                        }
                    }
                }
                else
                {
                    IRecontruction = new ImageReconstruction();
                }
            }
        }
        public void SetImageReconstruction(string Path2Lib)
        {
            IRecontruction = new ImageReconstruction();
            try
            {
                IRecontruction.loadMagicMatrix(Path2Lib);
            }
            catch (Exception e)
            {
                Debug.WriteLine("No inverse matrix in: " + Path2Lib);
            }
        }
        public void SetReference()
        {
            if (IRecontruction != null)
            {
                IRecontruction.SetRef(LastData);
            }
        }
        #endregion


        #region Serial_Device
        public void SerialSend(string target, string msg)
        {
            switch (target)
            {
                case "zmodule":
                    if (ContactZModule.IsOpen())
                    {
                        BusySerial = true;
                        ContactZModule.Send(msg);
                    }
                    break;
                case "currentsourcetester":
                    if (CurrentSourceTester.IsOpen())
                    {
                        BusySerial = true;
                        CurrentSourceTester.Send(msg);
                    }
                    break;
                case "robot":
                    if (Robot.IsOpen())
                    {
                        BusySerial = true;
                        Robot.Send(msg);
                    }
                    break;
            }
        }
        public void SerialOpen(string target, string port, string baud)
        {
            bool portExist=false;
            var portNames = System.IO.Ports.SerialPort.GetPortNames();

            foreach (var p in portNames)
            {
                if (port.ToUpper()==p)
                {
                    portExist = true;
                }
            }

            if (portExist)
            {
                switch (target)
                {
                    case "zmodule":
                        if (ContactZModule == null)
                        {
                            ContactZModule = new SerialDevice(port);
                            ContactZModule.sp.BaudRate = Convert.ToInt32(baud);
                            ContactZModule.OnDataReceived += new SerialDevice.OnDataReceivedHandler(ContactZModule_OnDataReceived);
                        }
                        if (!ContactZModule.IsOpen())
                        {
                            ContactZModule.Open();
                        }
                        break;
                    case "currentsourcetester":
                        if (CurrentSourceTester == null)
                        {
                            CurrentSourceTester = new SerialDevice(port);
                            CurrentSourceTester.sp.BaudRate = Convert.ToInt32(baud);
                            CurrentSourceTester.OnDataReceived += new SerialDevice.OnDataReceivedHandler(CurrentSourceTester_OnDataReceived);
                        }
                        if (!CurrentSourceTester.IsOpen())
                        {
                            CurrentSourceTester.Open();
                        }
                        break;
                    case "robot":
                        if (Robot == null)
                        {
                            Robot = new SerialDevice(port);
                            Robot.sp.BaudRate = Convert.ToInt32(baud);
                            Robot.OnDataReceived += new SerialDevice.OnDataReceivedHandler(Robot_OnDataReceived);
                        }
                        if (!Robot.IsOpen())
                        {
                            Robot.Open();
                        }
                        break;
                }
            }
        }
        public string SerialIsOpen()
        {
            string output = "";
            if (CurrentSourceTester != null)
            {
                if (CurrentSourceTester.sp.IsOpen)
                {
                    output += "currentsourcetester ";
                }
            }
            if (Robot != null)
            {
                if (Robot.sp.IsOpen)
                {
                    output += "robot ";
                }
            }
            if (ContactZModule != null)
            {
                if (ContactZModule.sp.IsOpen)
                {
                    output += "zmodule ";
                }
            }
            return output;
        }
        public void SerialClose(string target)
        {
            if ((CurrentSourceTester != null) && (target == "currentsourcetester"))
            {
                if (CurrentSourceTester.sp.IsOpen)
                {
                    CurrentSourceTester.Close();
                }
            }
            if ((Robot != null) && (target == "robot"))
            {
                if (Robot.sp.IsOpen)
                {
                    Robot.Close();
                }
            }
            if ((ContactZModule != null) && (target == "zmodule"))
            {
                if (ContactZModule.sp.IsOpen)
                {
                    ContactZModule.Close();
                }
            }
        }

        void Robot_OnDataReceived(object sender, EventArgs e)
        {
            //sends message to the debug output window 
            robot_buffer += Robot.sp.ReadExisting();

            string[] sss = robot_buffer.Split('\n');

            for (int i = 0; i < sss.Length; i++)
            {
                string serial_msg = sss[i];
                if (serial_msg.Contains("done"))
                {
                    BusySerial = false;
                }
                Debug.WriteLine("Robot " + " -> " + serial_msg);

                //writes logs into the oeit raw log file
                if (oeitfile == null)
                {
                    //creates a new oeit structure if oeit equal null
                    oeitfile = new oeit();
                }
                oeitfile.AddLogEntry("Robot " + "\t + e.Message");
                EventArgsMsg ee = new EventArgsMsg("Robot", serial_msg);
                //triggers the message function of the GUI or other
                if (OnMessage != null)
                    OnMessage(null, ee);
            }
            if (robot_buffer.Length != 0)
            {
                if (robot_buffer[robot_buffer.Length - 1] == '\n')
                {
                    robot_buffer = "";
                }
                else
                {
                    robot_buffer = sss[sss.Length - 1];
                }
            }
        }

        void CurrentSourceTester_OnDataReceived(object sender, EventArgs e)
        {
            //sends message to the debug output window 
            currentsourcetester_buffer += CurrentSourceTester.sp.ReadExisting();
            string[] sss = currentsourcetester_buffer.Split('\n');

            for (int i = 0; i < sss.Length; i++)
            {
                string serial_msg = sss[i];
                if (serial_msg.Contains("done"))
                {
                    BusySerial = false;
                }
                Debug.WriteLine("Current source tester " + " -> " + serial_msg);

                //writes logs into the oeit raw log file
                if (oeitfile == null)
                {
                    //creates a new oeit structure if oeit equal null
                    oeitfile = new oeit();
                }
                oeitfile.AddLogEntry("Current source tester " + "\t + e.Message");
                EventArgsMsg ee = new EventArgsMsg("CurrentSourceTester", serial_msg);
                //triggers the message function of the GUI or other
                if (OnMessage != null)
                    OnMessage(null, ee);
            }
            if (currentsourcetester_buffer.Length != 0)
            {
                if (currentsourcetester_buffer[currentsourcetester_buffer.Length - 1] == '\n')
                {
                    currentsourcetester_buffer = "";
                }
                else
                {
                    currentsourcetester_buffer = sss[sss.Length - 1];
                }
            }
        }

        void ContactZModule_OnDataReceived(object sender, EventArgs e)
        {
            //sends message to the debug output window 
            zmodule_buffer += ContactZModule.sp.ReadExisting();
            string[] sss = zmodule_buffer.Split('\n');

            for (int i = 0; i < sss.Length; i++)
            {
                string serial_msg = sss[i];

                if (serial_msg.Contains("done"))
                {
                    BusySerial = false;
                }
                Debug.WriteLine("ContactZModule " + " -> " + serial_msg);

                //writes logs into the oeit raw log file
                if (oeitfile == null)
                {
                    //creates a new oeit structure if oeit equal null
                    oeitfile = new oeit();
                }
                oeitfile.AddLogEntry("ContactZModuler " + "\t + e.Message");
                EventArgsMsg ee = new EventArgsMsg("ContactZModuler", serial_msg);
                //triggers the message function of the GUI or other
                if (OnMessage != null)
                    OnMessage(null, ee);
            }
            if (zmodule_buffer.Length != 0)
            {
                if (zmodule_buffer[zmodule_buffer.Length - 1] == '\n')
                {
                    zmodule_buffer = "";
                }
                else
                {
                    zmodule_buffer = sss[sss.Length - 1];
                }
            }
        }
        #endregion

        public double[] GetComplexImpedance(int[] I, int[] Q)
        {
            switch (DeviceName)
            {
                case "st_1_0.12_3.0_A":
                    return IQDataProcessor.GetComplexImpedance(I, Q, ToVoltParameter, Frequency);
                    break;
                case "st_1_0.12_3.0_B":
                    return IQDataProcessor.GetComplexImpedance(I, Q, ToVoltParameter, Frequency);
                    break;
                case "st_1_0.111_2.42_B":
                    return IQDataProcessor2.GetComplexImpedance(I, Q, ToVoltParameter, Frequency);
                    break;
                default:
                    return IQDataProcessor.GetComplexImpedance(I, Q, ToVoltParameter, Frequency);
            }
        }

        public void CheckIfConfigurationChanged()
        {
            try
            {
                string[] last = System.IO.File.ReadAllLines("CurrentParameter.txt");
                string PathPrev = oeitfile.DirPath + "\\raw\\config\\config" + oeitfile.ConfigPointer.ToString() + ".txt";
                bool idendical = true;
                if (System.IO.File.Exists(PathPrev))
                {
                    string[] previous = System.IO.File.ReadAllLines(PathPrev);


                    for (int i = 0; i < last.Length; i++)
                    {
                        if (last[i] != previous[i])
                        {
                            idendical = false;
                        }
                    }

                    if (idendical == false)
                    {
                        oeitfile.AddConfig(last);
                    }
                }
                else
                {
                    oeitfile.AddConfig(last);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }

        }

    }
}
